package com.ruoyi.web.controller.system;

import com.ruoyi.system.domain.ProjectScenarioAction;
import com.ruoyi.system.domain.ProjectScenarioRule;
import com.ruoyi.system.domain.ScenarioActionJournal;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

import javax.validation.constraints.NotNull;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;

@Slf4j
@RestController
@RequestMapping("/system/project.v2")
public class ProjectScenarioActionController extends BaseController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    IProjectScenarioRuleService projectScenarioRuleService;

    @Autowired
    IProjectScenarioActionService projectScenarioActionService;

    @Autowired
    IMonitorRuleService monitorRuleService;

    @Autowired
    IScenarioActionJournalService scenarioActionJournalService;

    @Autowired
    IProjectService projectService;

    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;

    @PreAuthorize("@ss.hasPermi('system:project:scenario:action:add')")
    @PostMapping(value = "/scenario/action/add", produces = "application/json;charset=UTF-8")
    @Log(title = "场景联动动作", businessType = BusinessType.INSERT)
    public AjaxResult addAction(@RequestBody @Validated(Create.class) ProjectScenarioAction projectScenarioAction) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", projectScenarioAction.getRuleId());
        ProjectScenarioRule projectScenarioRule = projectScenarioRuleService.retrieve(queryVo);
        if (projectScenarioRule == null) {
            return AjaxResult.error("没有找到指定的场景联动规则");
        }
        //TODO 验证当前用户是否授权该项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectScenarioRule.getProjectId());
        //LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String createBy = loginUser.getUsername();
        projectScenarioAction.setCompanyId(companyId);
        projectScenarioAction.setCreateBy(createBy);
        projectScenarioAction.setCreateTime(new Date());
        Integer id = projectScenarioActionService.create(projectScenarioAction);
        if (id != null) {
            return AjaxResult.success(projectScenarioAction);
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:project:scenario:action:list')")
    @GetMapping(value = "/scenario/action/list", produces = "application/json;charset=UTF-8")
    public Object indexAction(@Validated(Select.class) ProjectScenarioAction projectScenarioAction) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("type", projectScenarioAction.getType());
        queryVo.filters.put("rule_id", projectScenarioAction.getRuleId());
        queryVo.filters.put("rule_name", projectScenarioAction.getRuleName());
        startPage();
        List<ProjectScenarioAction> projectScenarioActions = projectScenarioActionService.index(queryVo);
        return getDataTable(projectScenarioActions);
    }

    @PreAuthorize("@ss.hasPermi('system:project:scenario:action:query')")
    @GetMapping(value = "/scenario/action/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieveAction(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        ProjectScenarioAction projectScenarioAction = projectScenarioActionService.retrieve(queryVo);
        if (projectScenarioAction == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        return AjaxResult.success(projectScenarioAction);
    }

    @PreAuthorize("@ss.hasPermi('system:project:scenario:action:edit')")
    @Log(title = "场景联动规则", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/scenario/action/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult editAction(@RequestBody @Validated(Update.class) ProjectScenarioAction projectScenarioAction) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", projectScenarioAction.getId());
        ProjectScenarioAction target = projectScenarioActionService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        projectScenarioAction.setCompanyId(target.getCompanyId());
        if (projectScenarioActionService.update(projectScenarioAction)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:project:scenario:action:remove')")
    @Log(title = "场景联动规则", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/scenario/action/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult removeAction(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        if (projectScenarioActionService.delete(queryVo)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
    @PreAuthorize("@ss.hasPermi('system:project:scenario:action:journal:list')")
    @GetMapping(value = "/scenario/action/journal/list", produces = "application/json;charset=UTF-8")
    public Object indexActionJournal(@Validated(Select.class) ScenarioActionJournal scenarioActionJournal) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("device_id", scenarioActionJournal.getDeviceId());
        queryVo.filters.put("device_name", scenarioActionJournal.getDeviceName());
        queryVo.filters.put("project_id", scenarioActionJournal.getProjectId());
        queryVo.filters.put("project_name", scenarioActionJournal.getProjectName());
        queryVo.filters.put("scenario_rule_id", scenarioActionJournal.getScenarioRuleId());
        queryVo.filters.put("scenario_rule_name", scenarioActionJournal.getScenarioRuleName());
        queryVo.filters.put("scenario_action_id", scenarioActionJournal.getScenarioActionId());
        queryVo.filters.put("state", scenarioActionJournal.getState());
        queryVo.filters.put("start", scenarioActionJournal.getStart());
        queryVo.filters.put("end", scenarioActionJournal.getEnd());
        startPage();
        List<ScenarioActionJournal> scenarioActionJournals = scenarioActionJournalService.index(queryVo);
        return getDataTable(scenarioActionJournals);
    }
}
